package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result findAll() {
        String key = "cache:TypeList:List";
        //@ZYL：先查找缓存
        String shopTypeString = stringRedisTemplate.opsForList().leftPop(key);

        //@ZYL：缓存找到了就直接返回
        if (StrUtil.isNotBlank(shopTypeString)) {
            return Result.ok(JSONUtil.toList(shopTypeString,ShopType.class));
        }

        //@ZYL：缓存找不到(隐含逻辑：if判断失败了，此处相当于else部分 )，再找数据库
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
        stringRedisTemplate.opsForList().leftPush(key, JSONUtil.toJsonStr(shopTypeList));

        return Result.ok(shopTypeList);

    }
}
